<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 *  测温一体机相关接口
 */
class Aio extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    // 用户ID前缀
    private $teacherPrefix = "t";
    private $studentPrefix = "s";

    // 获取一体机任务
    public function get_aio_task(){
        $this->load->model("aioModel");

        // 获取一体机信息
        $facesluiceId = $this->post("facesluice_id");
        if(empty($facesluiceId)) {
            throw new Exception("一体机ID不能为空");
        }
        $aioInfo = $this->aioModel->get_aio_info_by_facesluice_id_without_school_id($facesluiceId);
        if(!$aioInfo) throw new Exception("一体机ID不存在");

        // 获取一体机任务
        $params['pageStart'] = 0;
        $params['pageSize']= 100;
        // $params['pageSize']= 5;
        $params['aioId'] = $aioInfo['id'];
        $params['taskState'] = AIO_TASK_STATE_NEW;
        $params['isDelete'] = 0;
        $params['orderBy'] = 'id ASC';

        $mTaskList = $this->aioModel->get_aio_task_list($params);
        // 返回值
        $ret = array();
        foreach($mTaskList as $task) {
            // 用户ID前缀，区分教师和学生
            $idPrefix = "";
            if($task['user_type'] == AIO_USER_TYPE_TEACHER) $idPrefix = $this->teacherPrefix;
            else if($task['user_type'] == AIO_USER_TYPE_STUDENT) $idPrefix = $this->studentPrefix;

            $taskContent = array();
            $taskContent['id'] = $task['id'];
            $taskContent['task_type'] = $task['task_type'];
            $taskContent['task_state'] = $task['task_state'];

            switch($task['task_type']) {
                case AIO_TASK_TYPE_ADD:
                case AIO_TASK_TYPE_UPDATE:
                    $taskContent['custom_id'] = $idPrefix. $task['user_id'];
                    $taskContent['name'] = $task['user_name'];
                    $taskContent['user_face_image'] = $task['user_face_image'];
                    break;
                case AIO_TASK_TYPE_DELETE:
                    $taskContent['custom_id'] = $idPrefix. $task['user_id'];
                    $taskContent['name'] = $task['user_name'];
                    break;
            }

            $ret[] = $taskContent;
        }
        // exit(json("", true, count($mTaskList)));
        exit(json("", true, $ret));
    }
    // 一体机任务回调
    public function aio_task_callback(){
        $this->load->model("aioModel");

        $taskId = $this->post('task_id');
        $infoArr = json_decode($this->post('info'), true);
        // 更新任务状态
        $update['task_state'] = $infoArr['result'] == 'ok' ? AIO_TASK_STATE_OK : AIO_TASK_STATE_FAIL;
        $update['task_state_desc'] = isset($infoArr['detail']) ? $infoArr['detail'] : '';
        $update['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(AioModel::$aioTaskTable, $update, "`id` = '{$taskId}'");

        // 返回‘设备DNS错误’，重新创建一条任务
        if($update['task_state_desc'] == 'get pic and connect URI IP error') {
            $taskInfo = $this->aioModel->get_aio_task_info($taskId);
            $insertData = array(
                'school_id' => $taskInfo['school_id'],
                'campus_id' => $taskInfo['campus_id'],
                'aio_id' => $taskInfo['aio_id'],
                'facesluice_id' => $taskInfo['facesluice_id'],
                'user_id' => $taskInfo['user_id'],
                'user_name' => $taskInfo['user_name'],
                'user_face_image' => $taskInfo['user_face_image'],
                'user_type' => $taskInfo['user_type'],
                'task_type' => $taskInfo['task_type'],
                'task_state' => AIO_TASK_STATE_NEW,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            );
            $this->db->insert(AioModel::$aioTaskTable, $insertData);
        }

        // 返回‘图片超过1M’，创建一条删除任务
        if($update['task_state_desc'] == 'get URI pic data len too long') {
            $taskInfo = $this->aioModel->get_aio_task_info($taskId);
            $insertData = array(
                'school_id' => $taskInfo['school_id'],
                'campus_id' => $taskInfo['campus_id'],
                'aio_id' => $taskInfo['aio_id'],
                'facesluice_id' => $taskInfo['facesluice_id'],
                'user_id' => $taskInfo['user_id'],
                'user_name' => $taskInfo['user_name'],
                'user_face_image' => '',
                'user_type' => $taskInfo['user_type'],
                'task_type' => AIO_TASK_TYPE_DELETE,
                'task_state' => AIO_TASK_STATE_NEW,
                'createtime' => date('Y-m-d H:i:s'),
                'updatetime' => date('Y-m-d H:i:s')
            );
            $this->db->insert(AioModel::$aioTaskTable, $insertData);
        }
    }

    // 学生签到接口
    public function student_sign(){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model("aioModel");
        $this->load->model("staffModel");
        // 获取学生信息
        $studentId = $this->post('user_id');
        if(empty($studentId)) {
            throw new Exception('参数错误');
        }

        // 检查ID，如果是老师则不考勤
        $idPrefix = substr($studentId, 0, 1);
        if($idPrefix == $this->teacherPrefix) return;
        else {
            if($idPrefix == $this->studentPrefix) {
                $studentId = str_replace($this->studentPrefix, "", $studentId);
            }
        }


        // 获取学生信息
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        if(!$studentInfo || $studentInfo['is_delete'] == 1 || $studentInfo['is_graduated'] == 1) throw new Exception("签到失败，找不到对应的学生");
        // 签到图片，base64
        $imageBase64 = $this->post("image", false);
        if(empty($imageBase64)) {
            throw new Exception('图片参数错误');
        }
        // 判断base64字符串是否有带前缀data:image/jpg;base64,
        if(strstr($imageBase64, 'data:image/') == false) {
            // 添加前缀
            $imageBase64 = 'data:image/jpg;base64,' . $imageBase64;
        }

        // 设备序列号
        $facesluiceId = $this->post('facesluice_id');
        if(empty($facesluiceId)) {
            throw new Exception('参数错误');
        }
        // 获取设备信息
        $aioInfo = $this->aioModel->get_aio_info_by_facesluice_id($studentInfo['school_id'], $facesluiceId);
        if(empty($aioInfo)) {
            throw new Exception('一体机id不存在');
        }

        // 签到时间，以一体机传来的时间为准
        // $signTime = date('Y-m-d H:i:s');
        $signTime = $this->post('time');
        if(empty($signTime)) {
            throw new Exception('参数错误：签到时间');
        }

        // 判断5分钟内是否有重复提交
        $hasSigned = 0;
        $signInfo = $this->classesModel->get_sign_info_by_createtime_aio($signTime, $studentInfo['id']);
        if($signInfo) {
            $hasSigned = 1;
        }
        // var_export($signInfo);exit;
    
        // base64
        // 写入图片
        require_once('vendor/autoload.php');
        $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".jpg";
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $client = new Upyun\Upyun($serviceConfig);
        $signImg = UP_URL. $fileName;
        try{
            $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
        } catch(Exception $e) {
            // 捕获同个图片名，上传多次报错
            // $signImg = $e->getMessage();
            throw new Exception("429 Too Many Requests");
        }
        // 写文件上传调试日志
        if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
        $brandInfo = $this->classesModel->get_brand_info_by_class($studentInfo['class_id']);

        // 如果是同步学校，设置sign_is_submit=1
        $schoolInfo = $this->schoolModel->get_school_info($studentInfo['school_id']);
        if($schoolInfo['school_from'] == X_DATA_HAOZHUANYE) {
            $insert['sign_is_submit'] = 1;
        } else {
            $insert['sign_is_submit'] = 0;
        }

        $temperature = $this->post('temperature');
        if(empty($temperature)) {
            throw new Exception('参数错误');
        }


        // 判断5分钟内是否有重复提交，或者是否温度异常
        if($hasSigned == 0 || $temperature > 37.2) {
            // 获取当前课程id
            // 获取本周课程
            $schedule = $this->classesModel->get_campus_schedule($studentInfo['campus_id']);
            $timeJson = json_decode($schedule['schedule_time_json'], true);
            // 获取当前时间
            // $currentTime = date("H:i:s");
            $currentTime = explode(' ', $signTime)[1];

            // 当前课程节数
            $courseIndex = 0;
            $courseStartTime = $courseEndTime = $signStartTimeNew = $signEndTimeNew = "";
            // 判断timejson是否为NULL
            if(null !== $timeJson){
                // 获取当前时间是第几节课
                foreach($timeJson as $timePoint) {
                    // 如为设置，默认为10
                    if(!isset($timePoint['sign_interval'])) {
                        $timePoint['sign_interval'] = 10;
                    }
                    // interval如为0，走班也设置为10
                    // 新版上课时间
                    $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                    $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - ($timePoint['sign_interval']) * 60) . ':00';
                    $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                    if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                        $courseIndex = $timePoint['timeslotInDay'];
                        $courseStartTime = $timePoint['beginTime'];
                        $courseEndTime = $classEnd;
                        if($timePoint['sign_interval'] == 0) {
                            $signStartTimeNew = '';
                            $signEndTimeNew = '';
                        } else {
                            $signStartTimeNew = $signStartNew;
                            $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                        }
                        break;
                    }
                }
                // 判断签到状态
                $state = SIGN_STATE_AIO;
                // 判断是否补签
                foreach($timeJson as $timePoint) {
                    // 如为设置，默认为10
                    if(!isset($timePoint['sign_interval'])) {
                        $timePoint['sign_interval'] = 10;
                    }
                    // interval如为0，走班也设置为10
                    // 新版上课时间
                    $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                    if(date('H:i') >= $timePoint['beginTime'] && date('H:i') <= $classEnd) {
                        $state = SIGN_STATE_AIO_SUPPLEMENT;
                        break;
                    }
                }
                // 处理走班interval设置为0的情况
                if($courseIndex == 0) {
                    foreach($timeJson as $timePoint) {
                        // 如为设置，默认为10
                        if(!isset($timePoint['sign_interval'])) {
                            $timePoint['sign_interval'] = 10;
                        }
                        if($timePoint['sign_interval'] == 0) {
                            // 新版上课时间
                            $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                            $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - 10 * 60) . ':00';
                            $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                            if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                                $courseIndex = $timePoint['timeslotInDay'];
                                $courseStartTime = $timePoint['beginTime'];
                                $courseEndTime = $classEnd;
                                if($timePoint['sign_interval'] == 0) {
                                    $signStartTimeNew = '';
                                    $signEndTimeNew = '';
                                } else {
                                    $signStartTimeNew = $signStartNew;
                                    $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                                }
                                break;
                            }
                        }
                    }
                }
            }
            // 如果太早签到，当做第一节课
            if($courseIndex == 0) {
                if(date('H') < 8) {
                    $courseIndex = 1;
                } else {
                    $courseIndex = 5;
                }
            }
            // 获取本周指定课程信息
            // $weekIndex = date("w", time());
            $weekIndex = date("w", strtotime($signTime));
            $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
            // 获取本次上课信息
            $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);

            // 入库，做个毛线逻辑
            $insert['school_id'] = $studentInfo['school_id'];
            $insert['class_id'] = $studentInfo['class_id'];
            $insert['course_id'] = $scheduleLesson ? $scheduleLesson['id'] : 0;
            $insert['student_id'] = $studentInfo['id'];
            $insert['student_card_number'] = $studentInfo['realcard'];
            $insert['brand_id'] = $brandInfo ? $brandInfo['id'] : 0;
            $insert['sign_type'] = SIGN_TYPE_AIO;
            $insert['state'] = $state;
            $insert['sign_img'] = $signImg;
            $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
            $insert['temperature'] = $temperature;
            $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
            $insert['facesluice_id'] = $facesluiceId;
            $this->db->insert(ClassesModel::$signTable, $insert);

            // 返回值
            $ret['name'] = $studentInfo['realname'];
            $ret['signId'] = $this->db->insert_id();

            // 插入考勤临时表
            $this->db->insert(ClassesModel::$signTempTable, $insert);

            // 发送模板消息
            $this->load->library('wxtemplate');

            $url = wx_url('pub/student_sign_detail/' . $ret['signId']);
            $data = array(
                'first' => array(
                    'value' => '家长您好，' . $studentInfo['realname'] . '同学已经成功签到'
                ),
                'keyword1' => array(
                    'value' => $classInfo['class_name']
                ),
                'keyword2' => array(
                    'value' => date("Y-m-d H:i:s", strtotime($signTime))
                ),
                'keyword3' => array(
                    'value' => $studentInfo['realname']
                )
            );
            $this->wxtemplate->send_template_msg_for_user($studentInfo['id'], BIND_TYPE_STUDENT, WX_TEMPLATE_SCHEDULE, $data, $url);

            if($temperature && $temperature > 37.2 && $temperature < TEMPERATURE_UNKNOWN) {
                // 获取该学生的班主任
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $masterCoach = $this->staffModel->get_master_coach_by_class($class['id']);
                if($masterCoach) {
                    $masterInfo = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
                } else {
                    $masterInfo = NULL;
                }
    
                if($masterInfo) {
                    // 发送体温模板消息给班主任
                    $url = wx_url('pub/student_sign_detail/' . $ret['signId']);
                    $temp = handle_temperature($temperature);
                    if($temp == '未知') {
                        $temperatureStr = '未知';
                    } else {
                        $temperatureStr = $temp . '℃';
                    }

                    $data = array(
                        'first' => array(
                            'value' => '您好，收到学生测温异常通知'
                        ),
                        'keyword1' => array(
                            'value' => $studentInfo['realname']
                        ),
                        'keyword2' => array(
                            'value' => $temperatureStr
                        ),
                        'keyword3' => array(
                            'value' => date("Y-m-d H:i:s", strtotime($signTime))
                        )
                    );
                    $this->wxtemplate->send_template_msg_for_user($masterInfo['id'], BIND_TYPE_TEACHER, WX_TEMPLATE_TEMPEARTURE, $data, $url);
                }
            }

        }

        exit(json("", true, $ret));
    }
}
